package cn.tedu._03_vehicle.base.filters;

import cn.tedu._03_vehicle.pojo.vo.UserRegQuery;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = {"/v1/vehicle/*"})//当前过滤器的名称（随便写），后面参数是需要过滤的路径
//过滤器的创建
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("初始化....");
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //过滤器的核心方法，权限校验，网站限流，记录日志
        log.debug("进入过滤器进行数据校验");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;//进行强转
        //HttpServletResponse是ServletResponse的子类，所以需要进行类型强转
        //获取会话
        HttpSession session = request.getSession();
        UserRegQuery userRegQuery=(UserRegQuery) session.getAttribute("user");//校验登录状态
        if (userRegQuery!=null){
            //有此行代码则表示放行
            //没有则表示不放行
            filterChain.doFilter(request,response);
        }else {
            response.sendRedirect("login.html");//未登录则跳转至登录页面
        }
    }
    @Override
    public void destroy() {
        log.debug("销毁....");
        Filter.super.destroy();
    }
}
